<template>
	<n-card>
		<template #header>
			<n-space>
				<n-button type="primary" @click="fetchMenuData">刷新菜单</n-button>
				<n-button type="primary" @click="addMenu">新增菜单</n-button>
				<n-button type="primary" @click="getMenuConfig"
					>查看微信服务器菜单</n-button
				>
				<n-button type="error" @click="deleteCustomMenu" :disabled="!hasMenu"
					>删除自定义菜单</n-button
				>
			</n-space>
		</template>

		<!-- 菜单列表 -->
		<n-data-table
			:columns="columns"
			:data="menuList"
			:row-key="(row) => row.id"
			:single-line="false"
			:pagination="false"
		/>

		<!-- 菜单编辑对话框 -->
		<n-modal v-model:show="showMenuModal">
			<n-card
				:title="modalTitle"
				style="
					width: 600px;
					height: 100%;
					position: fixed;
					right: 0px;
					top: 0px;
					overflow-y: auto;
				"
				:bordered="false"
				role="dialog"
				aria-modal="true"
			>
				<n-form :model="menuForm" :rules="menuRules" ref="menuFormRef">
					<n-form-item path="menuName" label="菜单名称">
						<n-input
							v-model:value="menuForm.menuName"
							placeholder="请输入菜单名称"
						/>
					</n-form-item>
					<n-form-item path="menuType" label="菜单类型">
						<n-select
							v-model:value="menuForm.menuType"
							:options="menuTypeOptions"
							placeholder="请选择菜单类型"
						/>
					</n-form-item>
					<n-form-item path="tagId" label="标签" v-if="menuForm.menuType === 1">
						<n-select
							v-model:value="selectedTagId"
							:options="
								tags.map((tag) => ({ label: tag.name, value: tag.tagId }))
							"
							placeholder="请选择标签"
							allowClear
						/>
					</n-form-item>
					<n-form-item
						path="matchRule"
						label="标签匹配规则"
						v-if="menuForm.menuType === 1"
					>
						<n-input
							type="textarea"
							v-model:value="menuForm.matchRule"
							placeholder="{tagId:102}"
						/>
					</n-form-item>
				</n-form>

				<div style="margin-top: 20px">
					<h4>菜单按钮</h4>
					<div v-if="menuForm.buttons && menuForm.buttons.length > 0">
						<div
							v-for="(button, buttonIndex) in menuForm.buttons"
							:key="buttonIndex + '-button'"
							class="menu-button-group"
						>
							<n-form :model="button" :rules="buttonRules" :label-width="100">
								<n-form-item path="name" label="按钮名称">
									<n-input
										v-model:value="button.name"
										placeholder="请输入按钮名称"
									/>
								</n-form-item>
								<n-form-item path="type" label="按钮类型">
									<n-select
										v-model:value="button.type"
										:options="buttonTypeOptions"
										placeholder="请选择按钮类型"
									/>
								</n-form-item>

								<!-- 根据按钮类型显示不同字段 -->
								<n-form-item
									path="key"
									label="按钮KEY"
									v-if="button.type === 'click'"
								>
									<n-input
										v-model:value="button.key"
										placeholder="请输入按钮KEY"
									/>
								</n-form-item>
								<n-form-item
									path="url"
									label="跳转链接"
									v-if="button.type === 'view'"
								>
									<n-input
										v-model:value="button.url"
										placeholder="请输入跳转链接"
									/>
								</n-form-item>
								<n-form-item
									path="appid"
									label="小程序AppID"
									v-if="button.type === 'miniprogram'"
								>
									<n-input
										v-model:value="button.appid"
										placeholder="请输入小程序AppID"
									/>
								</n-form-item>
								<n-form-item
									path="pagepath"
									label="小程序页面路径"
									v-if="button.type === 'miniprogram'"
								>
									<n-input
										v-model:value="button.pagepath"
										placeholder="请输入小程序页面路径"
									/>
								</n-form-item>
							</n-form>

							<!-- 子按钮 -->
							<div
								v-if="button.type !== 'miniprogram'"
								style="margin-left: 40px"
							>
								<div v-if="button.subButtons && button.subButtons.length > 0">
									<div
										v-for="(subButton, subIndex) in button.subButtons"
										:key="subIndex + '-subbutton'"
										class="sub-button-group"
									>
										<n-form
											:model="subButton"
											:rules="buttonRules"
											:label-width="80"
										>
											<n-form-item path="name" label="按钮名称">
												<n-input
													v-model:value="subButton.name"
													placeholder="请输入按钮名称"
												/>
											</n-form-item>
											<n-form-item path="type" label="按钮类型">
												<n-select
													v-model:value="subButton.type"
													:options="buttonTypeOptions"
													placeholder="请选择按钮类型"
												/>
											</n-form-item>

											<!-- 根据按钮类型显示不同字段 -->
											<n-form-item
												path="key"
												label="按钮KEY"
												v-if="subButton.type === 'click'"
											>
												<n-input
													v-model:value="subButton.key"
													placeholder="请输入按钮KEY"
												/>
											</n-form-item>
											<n-form-item
												path="url"
												label="跳转链接"
												v-if="subButton.type === 'view'"
											>
												<n-input
													v-model:value="subButton.url"
													placeholder="请输入跳转链接"
												/>
											</n-form-item>
											<n-form-item
												path="appid"
												label="小程序AppID"
												v-if="subButton.type === 'miniprogram'"
											>
												<n-input
													v-model:value="subButton.appid"
													placeholder="请输入小程序AppID"
												/>
											</n-form-item>
											<n-form-item
												path="pagepath"
												label="小程序页面路径"
												v-if="subButton.type === 'miniprogram'"
											>
												<n-input
													v-model:value="subButton.pagepath"
													placeholder="请输入小程序页面路径"
												/>
											</n-form-item>
										</n-form>
										<n-button
											text
											type="error"
											@click="removeSubButton(buttonIndex, subIndex)"
											>删除子按钮</n-button
										>
									</div>
								</div>
								<n-button
									@click="addSubButton(buttonIndex)"
									:disabled="button.subButtons && button.subButtons.length >= 5"
									>添加子按钮(最多5个)</n-button
								>
							</div>

							<n-button text type="error" @click="removeButton(buttonIndex)"
								>删除按钮</n-button
							>
						</div>
					</div>
					<n-button
						@click="addButton"
						:disabled="menuForm.buttons && menuForm.buttons.length >= 3"
						>添加一级按钮(最多3个)</n-button
					>
				</div>

				<template #footer>
					<n-space justify="end">
						<n-button @click="showMenuModal = false">取消</n-button>
						<n-button type="primary" @click="handleMenuSubmit">保存</n-button>
					</n-space>
				</template>
			</n-card>
		</n-modal>
	</n-card>
	<n-modal v-model:show="showMenuConfig">
		<n-card
			title="菜单配置"
			style="
				width: 600px;
				height: 100%;
				position: fixed;
				right: 0px;
				top: 0px;
				overflow-y: auto;
			"
			:bordered="false"
			role="dialog"
			aria-modal="true"
		>
			<n-code language="json" :code="menuConfig" highlight></n-code>
		</n-card>
	</n-modal>
</template>

<script setup>
	import { ref, reactive, computed, onMounted, h } from "vue"; // 添加 h 函数导入
	import { useMessage, NSpace, NButton, NTag } from "naive-ui"; // 导入需要的组件
	import menuApi from "@server/api/menuApi";
	import wechatTagApi from "@server/api/wechatTagApi";

	const message = useMessage();

	// 菜单列表数据
	const menuList = ref([]);
	const hasMenu = computed(() => menuList.value.length > 0);

	// 菜单类型选项
	const menuTypeOptions = [
		{ label: "自定义菜单", value: 0 },
		{ label: "个性化菜单", value: 1 },
	];

	// 按钮类型选项
	const buttonTypeOptions = [
		{ label: "点击", value: "click" },
		{ label: "网页链接", value: "view" },
		{ label: "小程序", value: "miniprogram" },
	];

	// 表格列配置
	const columns = [
		{ title: "菜单名称", key: "menuName" },
		{
			title: "菜单类型",
			key: "menuType",
			render: (row) =>
				h(
					NTag,
					{ type: row.menuType === 1 ? "warning" : "info" },
					{
						default: () => (row.menuType === 1 ? "个性化菜单" : "自定义菜单"),
					}
				),
		},
		{ title: "微信菜单ID", key: "menuId" },
		{ title: "匹配规则", key: "matchRule" },
		{
			title: "状态",
			key: "status",
			render: (row) =>
				h(
					NTag,
					{ type: row.status === 1 ? "success" : "default" },
					{
						default: () => (row.status === 1 ? "已发布" : "未发布"),
					}
				),
		},
		{
			title: "操作",
			key: "action",
			render: (row) =>
				h(NSpace, null, [
					h(
						NButton,
						{
							text: true,
							onClick: () => editMenu(row),
							disabled: row.menuType === 0,
						},
						{
							default: () => "编辑",
						}
					),
					h(
						NButton,
						{
							text: true,
							type: "error",
							onClick: () => deleteMenu(row),
							disabled: row.menuType === 0,
						},
						{
							default: () => "删除",
						}
					),
				]),
		},
	];

	// 对话框状态
	const showMenuModal = ref(false);
	const modalTitle = ref("新增菜单");
	const menuConfig = ref("");
	const showMenuConfig = ref(false);

	// 菜单表单数据
	const menuForm = reactive({
		id: "",
		menuId: "",
		menuName: "",
		menuType: 0,
		matchRule: "",
		status: 0,
		buttons: [],
	});

	// 菜单表单引用
	const menuFormRef = ref();

	// 菜单验证规则
	const menuRules = {
		menuName: [{ required: true, message: "请输入菜单名称", trigger: "blur" }],
		menuType: [{ required: true, message: "请选择菜单类型", trigger: "change" }],
	};

	// 按钮验证规则
	// 1. 修改按钮验证规则，添加名称长度限制
	const buttonRules = {
		name: [
			{ required: true, message: "请输入按钮名称", trigger: "blur" },
			{
				validator: (rule, value, callback) => {
					if (value) {
						// 计算字符数（1个汉字=2个字符）
						const charCount = Array.from(value).reduce((count, char) => {
							return count + (char.charCodeAt(0) > 255 ? 2 : 1);
						}, 0);
						if (charCount > 16) {
							callback(new Error("按钮名称不能超过16个字符（8个汉字）"));
						} else {
							callback();
						}
					} else {
						callback();
					}
				},
				trigger: "blur",
			},
		],
		type: [{ required: true, message: "请选择按钮类型", trigger: "change" }],
		key: [
			{
				required: (rule, value, callback) => {
					const form = rule.formInstance.model;
					if (form.type === "click" && !value) {
						callback(new Error("请输入按钮KEY"));
					} else {
						callback();
					}
				},
				trigger: "blur",
			},
		],
		url: [
			{
				required: (rule, value, callback) => {
					const form = rule.formInstance.model;
					if (form.type === "view" && !value) {
						callback(new Error("请输入跳转链接"));
					} else {
						callback();
					}
				},
				trigger: "blur",
			},
		],
		appid: [
			{
				required: (rule, value, callback) => {
					const form = rule.formInstance.model;
					if (form.type === "miniprogram" && !value) {
						callback(new Error("请输入小程序AppID"));
					} else {
						callback();
					}
				},
				trigger: "blur",
			},
		],
		pagepath: [
			{
				required: (rule, value, callback) => {
					const form = rule.formInstance.model;
					if (form.type === "miniprogram" && !value) {
						callback(new Error("请输入小程序页面路径"));
					} else {
						callback();
					}
				},
				trigger: "blur",
			},
		],
	};

	// 标签列数据
	const tags = ref([]);
	const selectedTagId = ref(null);
	const fetchTags = async () => {
		try {
			tags.value = await wechatTagApi.getTagList();
		} catch (error) {
			console.error("获取标签列表失败:", error);
			message.error("获取标签列表失败");
		}
	};
	// 获取菜单列表
	const fetchMenuData = async () => {
		try {
			const data = await menuApi.getMenuList();
			menuList.value = data || [];
			message.success("获取菜单列表成功");
		} catch (error) {
			console.error("获取菜单列表失败:", error);
			message.error("获取菜单列表失败");
		}
	};
	const removeButton = (index) => {
		menuForm.buttons.splice(index, 1);
	};
	const removeSubButton = (buttonIndex, subIndex) => {
		const button = menuForm.buttons[buttonIndex];
		if (button.subButtons) {
			button.subButtons.splice(subIndex, 1);
		}
	};
	// 新增菜单
	const addMenu = () => {
		modalTitle.value = "新增菜单";
		// 重置表单
		Object.assign(menuForm, {
			id: "",
			menuId: "",
			menuName: "",
			menuType: 0,
			matchRule: "",
			status: 0,
			buttons: [],
		});
		showMenuModal.value = true;
	};

	// 编辑菜单
	const editMenu = async (row) => {
		modalTitle.value = "编辑菜单";
		try {
			// 获取菜单详情
			const detail = await menuApi.getMenuDetail(row.id);
			// 深拷贝避免直接修改原始数据
			Object.assign(menuForm, JSON.parse(JSON.stringify(detail)));
			// 确保buttons数组存在
			if (!menuForm.buttons) {
				menuForm.buttons = [];
			}
			showMenuModal.value = true;
		} catch (error) {
			console.error("获取菜单详情失败:", error);
			message.error("获取菜单详情失败");
		}
	};

	// 添加一级按钮
	// 2. 修改添加一级按钮函数，添加数量限制
	const addButton = () => {
		if (!menuForm.buttons) {
			menuForm.buttons = [];
		}
		// 检查一级按钮数量是否达到上限
		if (menuForm.buttons.length >= 3) {
			message.warning("一级菜单最多只能创建3个");
			return;
		}
		// 检查总菜单数量是否达到上限
		const totalButtons = menuForm.buttons.reduce((total, button) => {
			return total + 1 + (button.subButtons ? button.subButtons.length : 0);
		}, 0);
		if (totalButtons >= 18) {
			message.warning("总菜单数量不能超过18个");
			return;
		}
		menuForm.buttons.push({
			id: "",
			menuId: "",
			parentId: 0,
			name: "",
			type: "click",
			key: "",
			url: "",
			mediaId: "",
			articleId: "",
			appid: "",
			pagepath: "",
			sort: menuForm.buttons.length + 1,
			subButtons: [],
		});
	};

	// 3. 修改添加子按钮函数，添加数量限制
	const addSubButton = (buttonIndex) => {
		const button = menuForm.buttons[buttonIndex];
		if (!button.subButtons) {
			button.subButtons = [];
		}
		// 检查子按钮数量是否达到上限
		if (button.subButtons.length >= 5) {
			message.warning("每个一级菜单下的二级菜单最多5个");
			return;
		}
		// 检查总菜单数量是否达到上限
		const totalButtons = menuForm.buttons.reduce((total, btn) => {
			return total + 1 + (btn.subButtons ? btn.subButtons.length : 0);
		}, 0);
		if (totalButtons >= 18) {
			message.warning("总菜单数量不能超过18个");
			return;
		}
		button.subButtons.push({
			id: "",
			menuId: "",
			parentId: button.id || 0,
			name: "",
			type: "click",
			key: "",
			url: "",
			mediaId: "",
			articleId: "",
			appid: "",
			pagepath: "",
			sort: button.subButtons.length + 1,
		});
	};

	// 4. 修改保存菜单函数，添加完整的数量验证
	const handleMenuSubmit = async () => {
		try {
			// 简单验证按钮数量
			if (!menuForm.buttons || menuForm.buttons.length === 0) {
				message.warning("请至少添加一个按钮");
				return;
			}

			// 验证一级按钮数量
			if (menuForm.buttons.length > 3) {
				message.warning("一级菜单最多只能创建3个");
				return;
			}

			// 验证每个一级菜单下的子按钮数量
			for (let i = 0; i < menuForm.buttons.length; i++) {
				const button = menuForm.buttons[i];
				if (button.subButtons && button.subButtons.length > 5) {
					message.warning(`第${i + 1}个一级菜单下的二级菜单数量超过5个限制`);
					return;
				}
			}

			// 验证总菜单数量
			const totalButtons = menuForm.buttons.reduce((total, button) => {
				return total + 1 + (button.subButtons ? button.subButtons.length : 0);
			}, 0);
			if (totalButtons > 18) {
				message.warning(`总菜单数量不能超过18个，当前已添加${totalButtons}个`);
				return;
			}

			// 根据菜单类型调用不同的API
			if (menuForm.menuType === 0) {
				// 自定义菜单
				await menuApi.createCustomMenu(menuForm);
				message.success("自定义菜单创建成功");
			} else {
				// 个性化菜单
				if (!menuForm.matchRule) {
					message.warning("请输入个性化菜单的匹配规则");
					return;
				}
				await menuApi.createConditionalMenu(menuForm);
				message.success("个性化菜单创建成功");
			}

			showMenuModal.value = false;
			fetchMenuData();
		} catch (error) {
			console.error("保存菜单失败:", error);
			message.error("保存菜单失败");
			showMenuModal.value = false;
		}
	};

	// 删除菜单
	const deleteMenu = async (menu) => {
		try {
			if (confirm(`确定要删除菜单 "${menu.menuName}" 吗？`)) {
				if (menu.menuType === 1) {
					// 删除个性化菜单
					await menuApi.deleteConditionalMenu(menu.id);
				} else {
					// 删除自定义菜单（但实际不应从这里调用，因为删除自定义菜单会删除所有）
					message.warning('请使用顶部的"删除自定义菜单"按钮删除所有自定义菜单');
					return;
				}
				message.success("菜单删除成功");
				fetchMenuData();
			}
		} catch (error) {
			console.error("删除菜单失败:", error);
			message.error("删除菜单失败");
		}
	};

	// 删除自定义菜单（所有菜单）
	const deleteCustomMenu = async () => {
		try {
			if (
				confirm(
					"确定要删除所有自定义菜单吗？此操作将删除所有自定义菜单和个性化菜单！"
				)
			) {
				await menuApi.deleteCustomMenu();
				message.success("自定义菜单删除成功");
				fetchMenuData();
			}
		} catch (error) {
			console.error("删除自定义菜单失败:", error);
			message.error("删除自定义菜单失败");
		}
	};

	// 获取微信服务器上的菜单配置
	const getMenuConfig = async () => {
		try {
			const config = await menuApi.getMenuConfig();
			menuConfig.value = JSON.stringify(config, null, 2);
			console.log("微信服务器菜单配置:", menuConfig.value);
			showMenuConfig.value = true;
		} catch (error) {
			console.error("获取菜单配置失败:", error);
			message.error("获取菜单配置失败");
		}
	};

	// 组件挂载时加载数据
	onMounted(() => {
		fetchMenuData();
		fetchTags();
	});
	watch(
		() => selectedTagId.value,
		(newType) => {
			menuForm.matchRule = `{tag_id:${newType}}`;
		}
	);
</script>

<style scoped>
	.menu-button-group {
		border: 1px solid #e0e0e0;
		padding: 10px;
		margin-bottom: 10px;
		border-radius: 4px;
	}

	.sub-button-group {
		border: 1px solid #f0f0f0;
		padding: 10px;
		margin-bottom: 10px;
		border-radius: 4px;
	}
</style>